package com.liumin.comlink.http.intercepter;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;


import com.liumin.publiclib.helper.ContextApp;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import okhttp3.Interceptor;
import okhttp3.Response;

/**
* 接收并保存cookie
* 2019/12/25 10:27
* @author LiuWeiHao
*/
public class ReceivedCookiesInterceptor implements Interceptor {

    public ReceivedCookiesInterceptor() {
        super();
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = chain.proceed(chain.request());
        //这里获取请求返回的cookie
        if (!response.headers("Set-Cookie").isEmpty()) {
            List<String> headers = response.headers("Set-Cookie");
            Set<String> cookieSet = new HashSet<>();
            for (String head : headers) {
                Log.i("----", "---setCookie:" + head);
                cookieSet.add(head);
            }
            SharedPreferences sharedPreferences = ContextApp.app().getSharedPreferences("Cookie", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putStringSet("cookieSet", cookieSet);
            editor.commit();
        }
        return response;
    }

}
